/**
 * @description 利用js实现链表
 * @author 大肘子
 */

class ListNode{
    constructor(element){
        this.value = element
        this.next = null
    }
}

class LinkList{
    constructor(){
        this.head = null
        this.size = 0
    }
    append(value){
        const ele = new ListNode(value)
        if(this.size == 0){
            this.head = ele
        }else{
            const pre = this.getnode(this.size - 1)
            pre.next = ele
        }
        this.size++
    }
    appendAt(index,value){
        if(index < 0 || index > this.size){
            return new Error('out of range')
        }
        const ele = new ListNode(value)
        let cur = this.head
        if(index == 0){
            ele.next = cur
            this.head = ele
        }else{
            const pre = this.getnode(index - 1)
            ele.next = pre.next
            pre.next = ele
        }
        this.size ++
    }
    remove(index){
        if(index < 0 || index >= this.size){
            return new Error('out of range')
        }
        let cur = this.head
        if(index == 0){
            this.head = cur.next
        }else{
            const pre = this.getnode(index - 1)
            cur = pre.next
            pre.next = cur.next
        }
        this.size --
    }
    indexOf(value){
        let cur = this.head
        let index = -1
        for(let i = 0;i<this.size;i++){
            if(cur.value == value){
                index = i
            }
            cur = cur.next
        }
        return index
    }
    getnode(index){
        if(index < 0 || index >= this.size){
            return new Error('out of range')
        }
        let node = this.head
        if(index != 0){
            for(let i = 0;i<index;i++){
                node = node.next
            }
        }
        return node
    }
}


var linklist = new LinkList()
linklist.append(1)
linklist.append(2)
linklist.append(3)
// linklist.appendAt(0,0)
// linklist.appendAt(4,4)
// linklist.appendAt(1,0.5)
// linklist.remove(0)
// linklist.remove(0)
// linklist.remove(1)
// console.log(linklist.indexOf(3))
// console.dir(linklist,{
//     depth:100
// })

